import threading
import time
import socket

addr = ("192.168.1.38", 60000)
isSending = False
th = None

s = socket.create_connection(addr)

def recv():
    try:
        while True:
            time.sleep(0.3)
            recv_data = s.recv(102400).decode('utf-8')
            print(f"\nMessage from server: {recv_data}\n>>> ", end = '')
    except ConnectionResetError as e:
        print("Error: Connection closed/reset by server.")
        return


def main():
    global s, th
    th = threading.Thread(target=recv)
    th.setDaemon(True)
    th.start()
    print("Entering a command line. type help to help, quit quit.")
    while True:
        print(">>> ", end = '')
        cmd = input('').lower().strip()
        if cmd == 'send':
            se = ''
            print("Enter the message that you want to send, press Ctrl+C and Enter in a new line to Stop")
            while True:
                try:
                    se += '\n' + input('send << ')
                except (EOFError, KeyboardInterrupt):
                    print('')
                    break
            s.sendall(se.encode('utf-8'))
        elif cmd == 'help':
            print("Usage:\n\thelp:show this message\n\tsend:send some datas to server;\n\tquit:exit")
        elif cmd == 'quit':
            s.sendall("quit".encode('utf-8'))
            s.close()
            break
        elif cmd == '':
            continue
        else:
            print("Bad command!!")

if __name__ == '__main__':
    main()
